package com.kaesun.ufit.hardware;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import android.os.Message;

import com.kaesun.ufit.serialport.SerialPort;
import com.kaesun.ufit.treadmill.MainApplication;
import com.kaesun.ufit.treadmill.WeakRefHandler;

public class RfidReader {

	public static final int LEN_USERID = 8;

	private static final String DEVICE_RFID_READER = "/dev/ttyO1";
	private static final int BAUDRATE_RFID_READER = 115200;

	private SerialPort mSerialPort = null;
	private ReadThread mReadThread = null;
	private WeakRefHandler mHandler = null;

	public void start() {
		if (null == mSerialPort) {
			try {
				mSerialPort = new SerialPort(new File(DEVICE_RFID_READER), BAUDRATE_RFID_READER, 0);
				mReadThread = new ReadThread(mSerialPort);
				mReadThread.start();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void stop() {
		if (null != mReadThread) {
			mReadThread.interrupt();
			mReadThread = null;
		}
		if (null == mSerialPort) {
			mSerialPort.close();
			mSerialPort = null;
		}
	}

	public void setHandler(WeakRefHandler handler) {
		mHandler = handler;
	}


	private class ReadThread extends Thread {
		private InputStream mInputStream = null;

		public ReadThread(SerialPort sp) {
			mInputStream = sp.getInputStream();
		}

		@Override
		public void run() {
			super.run();

			if (null == mInputStream) {
				return;
			}

			byte[] buf = new byte[16];
			byte[] bufRead = new byte[16];
			byte[] bufSend = new byte[16];
			int size = 0, pos = 0;
			while (!isInterrupted()) {
				try {
					size = mInputStream.read(buf);
					System.arraycopy(buf, 0, bufRead, pos, size);
					pos += size;
					if (pos >= 10) {
						// 10 = stx + data[7:0] + etx
						if ((0x02 == bufRead[0]) && (0x03 == bufRead[9])) {
							if (null != mHandler) {
								System.arraycopy(bufRead, 1, bufSend, 0, LEN_USERID);
								mHandler.sendMessage(Message.obtain(mHandler, MainApplication.HANDLER_RX_RFIDREADER, LEN_USERID, 0, bufSend));
							}
						}
						pos = 0;
					}
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}
		}
	}
}
